package com.jman.register.service;

import cn.hutool.core.util.StrUtil;
import com.jman.register.clients.Agent;
import com.jman.register.clients.UserClients;
import com.jman.register.domain.User;
import com.jman.register.dto.RegisterFormDTO;
import com.jman.register.dto.Result;
import com.jman.register.dto.UserWithToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.jman.register.util.RegexUtils.isPasswordInvalid;
import static com.jman.register.util.RegexUtils.isPhoneInvalid;

@Service
public class RegisterService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserClients clients;

    public Result register(RegisterFormDTO registerFormDTO) {
        //获取表单信息
        String phone = registerFormDTO.getPhone();
        String password = registerFormDTO.getPassword();
        String code = registerFormDTO.getCode();
        //获取后台数据
        User userInfo = new User();
        userInfo.setPhone(phone);
        userInfo.setPassword(password);
        UserWithToken userWithToken = Agent.saveUser(clients, userInfo);
        String codeGen = StrUtil.toString(stringRedisTemplate.opsForValue().get("register:code"));

        if (isPhoneInvalid(phone)) {
            //手机格式是否正确
            return Result.fail("输入手机号不合法!");
        } else if (isPasswordInvalid(password)) {
            //密码格式是否正确
            return Result.fail("密码只能是4~32位的字母、数字、下划线!");
        } else if (!codeGen.equalsIgnoreCase(code)) {
            //验证码输入是否正确
            System.out.println(codeGen);
            return Result.fail("验证码出错！");
        } else if (userWithToken == null) {
            //手机号是否已经注册过
            return Result.fail("当前用户已经存在!");
        }

        //返回token
        String token = userWithToken.getToken();
        return Result.ok(token);
    }
}
